package com.foton.designmodel.share.interceptor;


import com.foton.designmodel.share.session.SessionShare;
import com.foton.designmodel.share.session.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;


/**
 * 拦截器 ：1：解析用户token信息，2：存储共享变量
 */
@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private UserThreadLocal userThreadLocal;
    private List<SessionShare> sessionShareList = new ArrayList<>();


    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

        //1：校验是否有token参数
        String token = req.getHeader("token");
        log.info("request uri {}",req.getRequestURI());

        if(!StringUtils.isBlank(token)){
            //1:存储到共享变量
            userThreadLocal.add(sessionShareList.get(new Random(sessionShareList.size()).nextInt()));
            return true;
        }
        res.setContentType("application/json;charset=utf-8");
        res.getWriter().println("身份校验失败！！！！");
        res.getWriter().close();

        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //释放资源
        userThreadLocal.remove();
    }

    @PostConstruct
    public void init(){
        sessionShareList.addAll(Arrays.asList(
                new SessionShare("阿拉丁","王晓晓","女",18,1),
                new SessionShare("蔡小美","李美丽","女",28,4),
                new SessionShare("白面书生","王一波","男",22,3),
                new SessionShare("黑旋风","李逵","男",32,7),
                new SessionShare("白龙吟","黄掌柜","男",32,7),
                new SessionShare("一枝独秀","陈迅尔","男",32,7),
                new SessionShare("天蚕土豆","李玉刚","男",32,7),
                new SessionShare("会飞的猪","张玉强","男",32,7)

        ));

    }
}
